<?php

class Users extends SM_ADMIN_Controller
{

    //assign $var to this field
    private $_data;

    public function __construct()
    {
        parent::__construct();
        $this->lang->load('user');
        $this->load->model('users_model');
        $this->load->model('role_model');
        $this->load->model('user_association_model');
    }

    public function index()
    {
        $this->load->library("pagination");
        $this->lang->load('user');
        $this->load->helper('users');

        /*
         * @todo breadcrumb
         */
        $breadcrumb = array();
        $breadcrumb[] = array('link' => admin_url('index'), 'name' => $this->lang->line('Home'));
        $breadcrumb[] = array(
                'link' => admin_url('users/index'),
                'name' => $this->lang->line('View user'),
                'class' => 'active'
            );
        $this->_data['breadcrumb'] = $breadcrumb;
        /*
         * @todo: Sort
         */
        $segment = 4;
        $column = $this->uri->segment(5, null);
        $sort = $this->uri->segment(6, null);
        $page = ($this->uri->segment($segment)) ? $this->uri->segment($segment) : 0;

        $this->_data['column'] = $column;
        $this->_data['sort'] = $sort;
        $this->_data['page'] = $page;

        $form = $this->input->post();
        if (isset($form['btn-Reset']) && $form['btn-Reset'] == 'Reset') {
            $this->session->unset_userdata('userSearch');
        }
        /*
         * @todo: Filter
         */
        if (isset($form['btn-Search']) && $form['btn-Search'] == 'Filter') {
            $userSearch = array(
                'textsearch' => isset($form['textsearch']) ? $form['textsearch'] : '',
            );

            $this->session->set_userdata('userSearch', $userSearch);
        }
        /*
         * @todo: Update publish, unpublish, delete action
         */

        if (isset($form['btn-Update']) && $form['btn-Update'] == 'Update') {
            if (!isset($form['checkListUser'])) {
                $message = $this->lang->line('error_at_least_user');
                $this->session->set_flashdata('cm_flash_message', cm_flash_message('error', $message));
                redirect_admin('users');
            }
        }
        /*
         * @todo: Session for filter
         */
        $usrSearchData = $this->session->userdata('userSearch');
        $conditionFilter = array();
        if (count($usrSearchData) && is_array($usrSearchData)) {
            if ($usrSearchData['textsearch']) {
                $conditionFilter += array('username' => $usrSearchData['textsearch']);
                $conditionFilter += array('first_name' => $usrSearchData['textsearch']);
                $conditionFilter += array('last_name' => $usrSearchData['textsearch']);
                $conditionFilter += array('email' => $usrSearchData['textsearch']);
            }
        }

        $user = $this->users_model->getAll(NULL, $conditionFilter);
        $url = admin_url('users/index');
        $config = config_pagination($url, $user->num_rows(), $segment);
        $this->pagination->initialize($config);

        $limit[0] = $config['per_page'];
        $limit[1] = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
        $order[0] = ($column) ? $column : 'userid';
        $order[1] = ($sort) ? $sort : 'ASC';

        $users = $this->users_model->viewUser(NULL, NULL, NULL, $limit, $order, $conditionFilter);
        $this->_data ['users'] = $users;
        $this->_data['pagination'] = $this->pagination->create_links(false, 'viewAdmin');

        //get Role
        $roleData = $this->getRole();

        //search Form
        $this->load->library('form_validation');
        $this->_data['frmSearch'] = usersFieldSearch($roleData, $usrSearchData);
        $this->_data['frmAction'] = usersFieldAction();
        $this->_data['action'] = 'admin/users/index/' . $page . '/' . $column . '/' . $sort;
        $this->load->view('layout/main', array('content' => 'users/index', 'data' => $this->_data));
    }

    public function delete($id = '')
    {
        $form = $this->input->post();
        if (isset($form['btn-Update']) && $form['btn-Update'] == 'Update') {
            if (!isset($form['checkListUser'])) {
                $message = $this->lang->line('error_at_least_user');
                $this->session->set_flashdata('cm_flash_message', cm_flash_message('error', $message));
                redirect_admin('users');
            }

            if (isset($form['event']) && $form['event'] == 2) {//delete
                foreach ($form['checkListUser'] as $key => $value) {
                    $result = $this->users_model->deleteUser($value);
                }
            }
        }

        if (isset($id) && !empty($id) && is_numeric($id)) {
            $result = $this->users_model->deleteUser($id);
        }$message = $this->lang->line('del_success');
        $this->session->set_flashdata('cm_flash_message', cm_flash_message('success', $message));
        redirect_admin('users');
    }

    private function getRole()
    {
        //get Role
        $roleData = array();
        $role = $this->role_model->getAll();
        if (count($role)) {
            $roleData[''] = $this->lang->line('pls_select_role');
            foreach ($role as $key => $value) {
                $roleData[$value->role_id] = $value->role_name;
            }
        }
        return $roleData;
    }

    private function imageAction($currentAvatar = '')
    {
        global $CFG;
        $error = array();
        $avatar = '';
        $avatar = $currentAvatar;
        $config ['upload_path'] = $CFG->item('folder_avatar');
        $dataUpload = doUpload('avatar', $config);
        if (isset($dataUpload ['upload_data'])) {
            if (file_exists($config ['upload_path'] . $avatar) && !empty($avatar)) {
                unlink($config ['upload_path'] . $avatar);
            }
            $avatar = $dataUpload ['upload_data'] ['file_name'];
        } else if (isset($dataUpload['error'])) {
            $error = array('msg' => $dataUpload['error']);
            return $error;
        }
        return $avatar;
    }

    public function edit($id)
    {
        /*
         * @todo breadcrumb
         */
        $breadcrumb = array();
        $breadcrumb[] = array('link' => admin_url('index'), 'name' => $this->lang->line('Home'));
        $breadcrumb[] = array(
                'link' => admin_url('users/edit/' . $id),
                'name' => $this->lang->line('Edit user'),
                'class' => 'active'
            );
        $this->_data['breadcrumb'] = $breadcrumb;

        $user = array();
        if (!empty($id) && is_numeric($id)) {
            $user = (array) $this->users_model->getInfo($id);
        }

        $this->load->library('form_validation');
        $this->load->helper('users');

        //set validate
        $validateUser = usersFieldValidate();
        unset($validateUser[1]);
        unset($validateUser[2]);
        $this->_data['error'] = '';
        $this->form_validation->set_rules($validateUser);
        if ($this->form_validation->run()) {
            $form = $this->input->post();
            $userCheck = $this->users_model->checkUsername($form['username'], $form['email']);

            if (count($userCheck) &&
                    ($userCheck->username != $user['username'] || $userCheck->email != $user['email'])) {
                $this->_data['error'] = $this->lang->line('dup_user');
            } else {
                //do upload image avatar
                $avatar = $this->imageAction($user ['avatar']);
                if (isset($avatar['msg']) && is_array($avatar) && $avatar != $user['avatar']) {
                    $this->_data['error'] = $avatar['msg'];
                }

                if (empty($this->_data['error'])) {
                    $condition = array('userid' => $id);
                    $updateData = array();
                    $updateData ['username'] = $form['username'];
                    $updateData ['first_name'] = $form['first_name'];
                    $updateData ['last_name'] = $form['last_name'];
                    $updateData ['email'] = $form['email'];
                    $updateData ['status'] = $form['status'];
                    $updateData ['avatar'] = $avatar;
                    $update = $this->users_model->updateUser($condition, $updateData);

                    //update Role
                    $checkRole = $this->role_model->getRoleUserByID($id);
                    if (count($checkRole)) {
                        $updateKey = array();
                        $updateKey ['role_id'] = $form['role_id'];
                        $update = $this->role_model->updateRoleUser($condition, $updateKey);
                    } else {
                        $insertData = array();
                        $insertData ['userid'] = $id;
                        $insertData ['role_id'] = $form['role_id'];
                        $insert = $this->role_model->createRoleUser($insertData);
                    }
                    $message = $this->lang->line('edit_success');
                    $this->session->set_flashdata('cm_flash_message', cm_flash_message('success', $message));
                    redirect_admin('users');
                }
            }
        }

        //get Role
        $roleData = $this->getRole();
        $frmUser = usersFieldForm($user, $roleData);
        unset($frmUser['password']);
        unset($frmUser['password_confirm']);
        $this->_data['form'] = $frmUser;
        $this->_data['action'] = 'admin/users/edit/' . $id;
        $this->_data['idUser'] = $id;
        $this->_data['head_title'] = $this->lang->line('Edit user');
        $this->load->view('layout/main', array('content' => 'users/form', 'data' => $this->_data));
    }

    public function add()
    {
        /*
         * @todo breadcrumb
         */
        $breadcrumb = array();
        $breadcrumb[] = array('link' => admin_url('index'), 'name' => $this->lang->line('Home'));
        $breadcrumb[] = array(
                'link' => admin_url('users/add'),
                'name' => $this->lang->line('Add user'),
                'class' => 'active'
            );
        $this->_data['breadcrumb'] = $breadcrumb;

        $this->load->library('form_validation');
        $this->load->helper('users');

        //set validate
        $this->form_validation->set_rules(usersFieldValidate());
        if ($this->form_validation->run()) {
            $form = $this->input->post();
            $user = $this->users_model->checkUsername($form['username'], $form['email']);

            if (count($user)) {
                $this->_data['error'] = $this->lang->line('dup_user');
            } else {
                //do upload image avatar
                $avatar = $this->imageAction();

                $insertData = array();
                $insertData ['username'] = $form['username'];
                $insertData ['password'] = md5($form['password']);
                $insertData ['first_name'] = $form['first_name'];
                $insertData ['last_name'] = $form['last_name'];
                $insertData ['email'] = $form['email'];
                $insertData ['status'] = $form['status'];
                $insertData ['created'] = time();
                $insertData ['avatar'] = $avatar;
                $insert = $this->users_model->createUser($insertData);
                if ($insert) {
                    $insertData = array();
                    $insertData ['userid'] = $insert;
                    $insertData ['role_id'] = $form['role_id'];
                    $insert = $this->role_model->createRoleUser($insertData);
                    $message = $this->lang->line('added_success');
                    $this->session->set_flashdata('cm_flash_message', cm_flash_message('success', $message));
                    redirect_admin('users');
                }
            }
        }
        //get Role
        $roleData = $this->getRole();

        $this->_data['form'] = usersFieldForm('', $roleData);
        $this->_data['action'] = 'admin/users/add';
        $this->_data['head_title'] = $this->lang->line('Add user');
        $this->load->view('layout/main', array('content' => 'users/form', 'data' => $this->_data));
    }

    public function checkStatus($id = '')
    {
        $form = $this->input->post();
        if (isset($form['btn-Update']) && $form['btn-Update'] == 'Update') {
            if (!isset($form['checkListUser'])) {
                $message = $this->lang->line('error_at_least_user');
                $this->session->set_flashdata('cm_flash_message', cm_flash_message('error', $message));
                redirect_admin('users');
            }

            if (isset($form['event'])) {//update multi
                $updateData = $condition = array();
                $updateData['status'] = $form['event'];
                $condition = array('userid' => $form['checkListUser']);
                $update = $this->users_model->updateUser($condition, $updateData, 'IN');
                if ($update) {
                    $message = $this->lang->line('edit_success');
                    $this->session->set_flashdata('cm_flash_message', cm_flash_message('success', $message));
                    redirect_admin('users');
                }
            }
        }

        if (!empty($id) && is_numeric($id)) {
            $user = (array) $this->users_model->getInfo($id);
            $updateData = array();
            $updateData ['status'] = ($user['status'] == 1) ? 0 : 1;
            $condition = array('userid' => $id);
            $update = $this->users_model->updateUser($condition, $updateData);
            $message = $this->lang->line('edit_success');
            $this->session->set_flashdata('cm_flash_message', cm_flash_message('success', $message));
            $uri = str_replace(base_url() . $this->uri->segment(1) . '/', '', $_SERVER['HTTP_REFERER']);
            redirect_admin($uri);
        }
    }

    public function changepwd($id)
    {
        $this->load->library('form_validation');
        $this->load->helper('users');
        /*
         * @todo breadcrumb
         */
        $breadcrumb = array();
        $breadcrumb[] = array('link' => admin_url('index'), 'name' => $this->lang->line('Home'));
        $breadcrumb[] = array(
                'link' => admin_url('users/changepwd/' . $id),
                'name' => $this->lang->line('ChangePwd'),
                'class' => 'active'
            );
        $this->_data['breadcrumb'] = $breadcrumb;

        //set validate
        $this->form_validation->set_rules(usersFieldPwdValidate());
        if ($this->form_validation->run()) {
            $form = $this->input->post();
            $updateData = array();
            $updateData ['password'] = md5($form['newpwd']);
            $condition = array('userid' => $id);
            $update = $this->users_model->updateUser($condition, $updateData);
            $message = $this->lang->line('changepwd_success');
            $this->session->set_flashdata('cm_flash_message', cm_flash_message('success', $message));
            redirect_admin('users');
        }

        $this->_data['form'] = usersFieldPwd();
        $this->_data['action'] = 'admin/users/changepwd/' . $id;
        $this->_data['idUser'] = $id;
        $this->_data['head_title'] = $this->lang->line('ChangePwd');
        $this->load->view('layout/main', array('content' => 'users/changepwd', 'data' => $this->_data));
    }

    public function importcsv()
    {
        $this->load->library('form_validation');
        $this->load->helper('users');

        /*
         * @todo breadcrumb
         */
        $breadcrumb = array();
        $breadcrumb[] = array('link' => admin_url('index'), 'name' => $this->lang->line('Home'));
        $breadcrumb[] = array(
                'link' => admin_url('users/importcsv'),
                'name' => $this->lang->line('Import_User'),
                'class' => 'active'
            );
        $this->_data['breadcrumb'] = $breadcrumb;

        $this->_data['form'] = userUploadCSVForm();
        $this->_data['action'] = 'admin/users/do_upload_csv';
        $this->_data['head_title'] = $this->lang->line('Import_User');
        $this->load->view('layout/main', array('content' => 'users/importcsv_form', 'data' => $this->_data));
    }

    function do_upload_csv()
    {
        ini_set('auto_detect_line_endings', true);

        $this->load->model('member_model');
        $config['upload_path'] = BASEPATH . '../public/files/';
        $config['allowed_types'] = 'csv';
        $config['max_size'] = '1024';

        $listRole = array("vendeur", "vendeur ics", "manager vendeur", "ia");

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('csv_file')) {
            $error = array('error' => $this->upload->display_errors());
            $this->session->set_flashdata('cm_flash_message', cm_flash_message('error', $error['error']));
            redirect_admin('users/importcsv');
        } else {
            $data = $this->upload->data();

            if (isset($data) && !empty($data)) {

                $fields = "c.member_name";
                $rs = $this->member_model->getAll(NULL, $fields)->result_array();

                $listID = array();
                foreach ($rs as $k => $v) {
                    $listID[$v['member_name']] = $v['member_name'];
                }
                $newCuid = array();
                $csvFile = $data['full_path'];
                if (($handle = fopen($csvFile, "r")) !== FALSE) {
                    $rows = 0;
                    while (($data = fgetcsv($handle, 10000, ';')) !== FALSE) {

                        $newCuid[$data[CSV_CUID]] = $data[CSV_CUID];

                        $insertData = array();
                        $updateData = array();
                        // do not import first records. That is title in csv file
                        if ($rows > 0 && !empty($data) && $data[CSV_CUID] != '') {

                            if(isset($data[CSV_NAME]) && trim($data[CSV_NAME]) != '') {
                                $insertData['lastname'] = $data[CSV_NAME];
                            }
                            if(isset($data[CSV_PRENAME]) && trim($data[CSV_PRENAME]) != '') {
                                $insertData['firstname'] = $data[CSV_PRENAME];
                            }
                            if(isset($data[CSV_CUID]) && trim($data[CSV_CUID]) != '') {
                                $insertData['member_name'] = $data[CSV_CUID];
                            }
                            $insertData['created'] = date('Y-m-d');
                            $insertData['updated'] = date('Y-m-d');

                            if(isset($data[CSV_FUNCTION]) && trim($data[CSV_FUNCTION]) != '') {
                                $insertData['function'] = $data[CSV_FUNCTION];
                            }
                            if(isset($data[CSV_MANAGER]) && trim($data[CSV_MANAGER]) != ''){
                                $insertData['manager'] = $data[CSV_MANAGER];
                            }
                            if(isset($data[CSV_AE]) && trim($data[CSV_AE]) != '') {
                                $insertData['ae'] = $data[CSV_AE];
                            }
                            if(isset($data[CSV_EMAIL]) && trim($data[CSV_EMAIL]) != '') {
                                $insertData['email'] = $data[CSV_EMAIL];
                            }
                            //$insertData['entreprise'] = $data[CSV_ENTREPRISE];
                            $insertData['entite'] = $data[CSV_ENTITE];

                            if (strtolower($data[CSV_ROLE]) == 'vendeur' || strtolower($data[CSV_ROLE]) == 'vendeur ics') {
                                $type = 0;
                            } else if (strtolower($data[CSV_ROLE]) == 'manager vendeur') {
                                $type = 1;
                            } else if (strtolower($data[CSV_ROLE]) == 'ia') {
                                $type = 2;
                            }

                            $insertData['type'] = $type;
                            $insertData['active'] = 1;

                            // not insert if have same CUID
                            if (!in_array($data[CSV_CUID], $listID)) {
                                if (in_array(strtolower($data[CSV_ROLE]), $listRole)) {
                                    $insertData['role'] = ucfirst($data[CSV_ROLE]);
                                    $this->member_model->createMember($insertData);
                                }
                            } else {

                                $updateData['lastname'] = $data[CSV_NAME];
                                $updateData['firstname'] = $data[CSV_PRENAME];
                                $updateData['updated'] = date('Y-m-d');
                                $updateData['ae'] = $data[CSV_AE];

                                $updateData['email'] = $data[CSV_EMAIL];

                                $updateData['entite'] = $data[CSV_ENTITE];
                                $updateData['type'] = $type;
                                $updateData['active'] = 1;

                                if (in_array(strtolower($data[CSV_ROLE]), $listRole)) {
                                    $updateData['role'] = ucfirst($data[CSV_ROLE]);
                                }

                                $conditions = array(
                                    'member_name' => $data[CSV_CUID]
                                );

                                $this->member_model->updateMember($conditions, $updateData);

                            }
                        }
                        ++$rows;
                    }
                    fclose($handle);
                }

                //inactive user not in file
                $userListToDisable = array();
                foreach ($listID as $cuid) {
                    if(!in_array($cuid, $newCuid)){
                        $userListToDisable[$cuid] = $cuid;
                    }
                }
                $this->member_model->disableUserlist($userListToDisable);

                // list all from user_association
                $rs_userid = $this->user_association_model->getAll();
                $listAssoc = array();
                foreach ($rs_userid as $v) {
                    $listAssoc[$v['owner_id']][] = $v['user_id'];
                }

                if (($handle = fopen($csvFile, "r")) !== FALSE) {
                    $rows = 0;
                    while (($data = fgetcsv($handle, 1000, ';')) !== FALSE) {
                        // insert user association
                        if ($rows > 0 && !empty($data) && $data[CSV_CUID] != '') {
                            $ownerId = $this->member_model->getMemberCuid($data[CSV_MANAGER]);
                            if(isset($data[CSV_MANAGER]) && isset($ownerId) && $ownerId->id != null) {

                                $objUser = $this->member_model->getMemberCuid($data[CSV_CUID]);
                                if (isset($objUser) && $objUser->id != null) {
                                    if ((isset($listAssoc[$ownerId->id])
                                            && in_array($objUser->id, $listAssoc[$ownerId->id]))) {
                                        // check archived
                                        // if archived == 1 we will update to 0
                                        // else do nothing.
                                        foreach ($rs_userid as $v) {
                                            if ($v['owner_id'] == $ownerId->id
                                                    && $v['user_id'] == $objUser->id
                                                    && $v['archived'] == 1) {
                                                $conditions = array(
                                                    'owner_id' => $ownerId->id,
                                                    'user_id' => $objUser->id,
                                                );
                                                $updateData = array (
                                                    'archived' => 0
                                                );
                                                $this->user_association_model
                                                        ->updateUserAssociaton($conditions, $updateData);
                                            }
                                        }
                                    } else {
                                        $insertAssociationData['owner_id'] = $ownerId->id;
                                        $insertAssociationData['user_id'] = $objUser->id;
                                        $insertAssociationData['archived'] = 0;
                                        $insertAssociationData['created'] = date('Y-m-d');
                                        if(isset($insertAssociationData)){
                                            $this->user_association_model->addUserAssociaton($insertAssociationData);
                                        }
                                    }
                                }
                            }
                        }
                        ++$rows;
                    }
                    fclose($handle);
                }
            }
            $message = $this->lang->line('Import_CSV_Success');
            $this->session->set_flashdata('cm_flash_message', cm_flash_message('success', $message));
            redirect_admin('users/importcsv');
        }
    }

}